import React, { useState } from "react";
import ReactQuill from "react-quill";
import "react-quill/dist/quill.snow.css";
import axios from "axios";
import { useLocation, useNavigate } from "react-router-dom";
import moment from "moment";
import {message,Modal} from 'antd'

const Write = () => {
  const state = useLocation().state;
  const [messageApi,contextHolder] = message.useMessage();
  const [title, setTitle] = useState(state?.title || "");
  const [value, setValue] = useState(state?.desc || "");
  const [img] = useState(state?.img || "");
  const [file, setFile] = useState(null);
  const [cat, setCat] = useState(state?.cat || "");
  const [isModalOpen, setIsModalOpen] = useState(false);
  const showModal = () => {
    setIsModalOpen(true);
  };
  const handleOk = () => {
    handleClick()
    setIsModalOpen(false);
  };
  const handleCancel = () => {
    setIsModalOpen(false);
  };

  const navigate = useNavigate()

  const upload = async () => {
    try {
      const formData = new FormData();
      formData.append("file", file);
      const res = await axios.post("/upload", formData);
      return res.data;
    } catch (err) {
      console.log(err);
    }
  };
  const handleClick = async () => {
    showModal()
    const imgUrl = await upload();
    const key = 'updatable';
    try {
      state
        ? await axios.put(`/posts/${state.id}`, {
            title,
            desc: value,
            cat,
            img: file ? imgUrl : img,
          })
        : await axios.post(`/posts/`, {
            title,
            desc: value,
            cat,
            img: file ? imgUrl : img,
            date: moment(Date.now()).format("YYYY-MM-DD HH:mm:ss"),
          });
          navigate("/")
          messageApi.open({
            key,
            type: 'success',
            content: '发布成功！',
          }); 
    } catch (err) {
      console.log(err);
    }
  };
  const cleanQuill = () =>{
    setTitle('')
    setValue('')
  }
  return (
    <div className="add">
      {contextHolder}
      <Modal title="提示" open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
        <p>是否确认发布！</p>
      </Modal>
      <div className="content">
        <input
          type="text"
          placeholder="Title"
          value={title}
          onChange={(e) => setTitle(e.target.value)}
        />
        <div className="editorContainer">
          <ReactQuill
            className="editor"
            theme="snow"
            value={value}
            onChange={setValue}
          />
        </div>
      </div>
      <div className="menu">
        <div className="item">
          <h1>发布</h1>
          <span>
            <b>状态: </b> 编辑
          </span>
          <span>
            <b>谁可以看: </b> 公开
          </span>
          <input
            style={{ display: "none" }}
            type="file"
            id="file"
            name=""
            onChange={(e) => setFile(e.target.files[0])}
          />
          <label className="file" htmlFor="file">
            点击上传图片
          </label>
          <div className="buttons">
            <button className="clean" onClick={cleanQuill}>清空</button>
            <button onClick={showModal}>发布</button>
          </div>
        </div>
        <div className="item">
          <h1>类型</h1>
          <div className="cat">
            <input
              type="radio"
              checked={cat === "study"}
              name="cat"
              value="study"
              id="study"
              onChange={(e) => setCat(e.target.value)}
            />
            <label htmlFor="study">学习</label>
          </div>
          <div className="cat">
            <input
              type="radio"
              checked={cat === "share"}
              name="cat"
              value="share"
              id="share"
              onChange={(e) => setCat(e.target.value)}
            />
            <label htmlFor="share">分享</label>
          </div>
          <div className="cat">
            <input
              type="radio"
              checked={cat === "mood"}
              name="cat"
              value="mood"
              id="mood"
              onChange={(e) => setCat(e.target.value)}
            />
            <label htmlFor="mood">随笔</label>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Write;
